import { BasePage, storage } from "../../common/index";
import SearchService from "../../services/search";
// let refreshTimer = null;
export default class IndexController extends BasePage {
  constructor(data) {
    super(data);
    this._registerPage(IndexController);
    this.searchService = new SearchService();
    this.storage = storage;
  }
  /**
   * 生命周期函数
   */
  onLoad(options) {
    // wx.clearStorage()
  }
  /**
   * 生命周期函数
   */
  onShow() {
    this.reloadPageData();
    console.log(
      this.storage.data.bookList,
      this.data.data,
      this.data.groupData
    );
  }
  reloadPageData(status) {
    const data = this.storage.data.bookList || [];
    const allData = {
      id: "all",
      name: "全部书籍",
      bookList: [],
    };
    let currentGroup = {};
    const groupData = this.storage.data.groups || [];
    let result = [];
    if (status) {
      currentGroup = this.data.currentGroup;
    } else {
      currentGroup = this.storage.data.currentGroup || null;
    }
    data.map((item) => {
      item.loadStatus = false;
    });
    data.map((item) => {
      allData.bookList.push(item.id);
    });
    if (groupData.length > 0) {
      currentGroup = currentGroup || allData;
      currentGroup.bookList.map((item) => {
        const book = data.find((d) => d.id == item);
        if (book) {
          result.push(book);
        }
      });
    } else {
      result = data;
    }
    this.data.data = result;
    this.data.allData = allData;
    this.data.groupData = groupData;
    this.data.currentGroup = currentGroup;
  }
  hideGroupModal() {
    this.data.groupModalStatus = false;
  }
  deleteGroup() {
    if (this.data.currentGroup.id != "all") {
      const bookList = [];
      const currentGroup = this.data.currentGroup;
      // 生成新数组
      currentGroup.bookList.map((item) => {
        if (item != this.data.currentBookId) {
          bookList.push(item);
        }
      });
      // 赋值给当前分组
      currentGroup.bookList = bookList;
      this.data.currentGroup = currentGroup;
      const groupData = this.storage.data.groups || [];
      const groupDataResult = [];
      groupData.map((item) => {
        if (item.id == currentGroup.id) {
          item = currentGroup;
        }
        if (item.bookList.length > 0) {
          groupDataResult.push(item);
        }
      });
      this.data.groupData = this.storage.data.groups = groupDataResult;
      this.reloadPageData(true);
    }
    this.data.groupModalStatus = false;
  }
  setDefaultGroup() {
    this.storage.data.currentGroup = this.data.currentGroup;
    // wx.showToast({
    //   title: "已设置为默认分组",
    //   icon: "success",
    //   duration: 1000,
    // });
  }
  /**
   * 打开分组弹窗
   */
  moveGroup(e) {
    this.data.currentBookId = e.detail.id;
    this.data.groupModalStatus = true;
  }
  /**
   * 改变分组
   */
  changeGroup(e) {
    if (e.currentTarget.dataset.id === "all") {
      const data = this.storage.data.bookList || [];
      this.data.data = data;
      this.data.currentGroup = this.data.allData;
    } else {
      this.data.currentGroup = this.data.groupData.find(
        (item) => item.id == e.currentTarget.dataset.id
      );
      this.setDefaultGroup();
      // this.storage.data.currentGroup = this.data.currentGroup;
      this.reloadPageData(true);
    }
  }
  /**
   * 选中分组
   * @param {*} e
   */
  checkGroup(e) {
    // 所有分组数据
    const groupData = this.data.groupData;
    // 从当前分组中移除
    const currentGroup = this.data.currentGroup;
    const bookList = [];
    currentGroup.bookList.map((item) => {
      if (item != this.data.currentBookId) {
        bookList.push(item);
      }
    });
    currentGroup.bookList = bookList;
    this.data.currentGroup = currentGroup;
    groupData.map((item) => {
      if (this.data.currentGroup.id == item.id) {
        item = this.data.currentGroup;
      }
      // 指定分组id
      if (item.id == e.currentTarget.dataset.id) {
        // 当前移动书籍
        const currentBookId = this.data.currentBookId;
        let bookId = item.bookList.find((id) => id == currentBookId);
        if (!bookId) {
          // 移动到指定的分组
          item.bookList.push(currentBookId);
        }
      }
    });
    this.data.groupData = this.storage.data.groups = groupData;
    this.data.showAddDialog = false;
    this.data.groupModalStatus = false;
    this.data.currentGroup = groupData.find(
      (item) => item.id == e.currentTarget.dataset.id
    );
    this.setDefaultGroup();
    this.reloadPageData(true);
  }
  /**
   * 删除小说
   */
  deleteCard(e) {
    const result = [];
    const bookList = this.storage.data.bookList || [];
    bookList.map((item) => {
      if (item.id != e.detail.id) {
        result.push(item);
      }
    });
    this.data.data = [];
    setTimeout(() => {
      this.storage.data.bookList = result;
      this.reloadPageData(true);
    }, 50);
  }
  /**
   * 查看详情
   */
  goToDetails(e) {
    const book = this.storage.data.bookList.find(
      (item) => item.id === e.detail.id
    );
    this.storage.data.currentBookDetail = book;
    wx.navigateTo({
      url: "/pages/detail/detail",
    });
  }

  goToContent(e) {
    const book = this.storage.data.bookList.find(
      (item) => item.id === e.detail.id
    );
    const dataList = this.data.data;
    const bookList = this.storage.data.bookList;
    dataList.map((item) => {
      if (item.id === e.detail.id) {
        item.isHaveUpdate = false;
      }
    });
    bookList.map((item) => {
      const b = dataList.find((d) => d.id === item.id);
      if (b) {
        item = b;
      }
    });

    this.data.data = dataList;
    this.storage.data.bookList = bookList;
    this.storage.data.currentBookDetail = book;
    this.storage.data.currentBookChapter =
      book.chapter[book.currentChapter || 0];
    wx.navigateTo({
      url: "/pages/content/content",
    });
  }

  /**
   * 置顶
   * @param {Object} e
   */
  goToTop(e) {
    if (this.data.groupData.length > 0 && this.data.currentGroup.id != "all") {
      wx.showToast({
        title: "分组暂不支持置顶",
        icon: "error",
        duration: 1000,
      });
      return;
    }
    const book = this.data.data.find((item) => item.id === e.detail.id);
    const bookList = this.storage.data.bookList || [];
    let result = [book];
    bookList.map((d) => {
      if (d.id != book.id) {
        result.push(d);
      }
    });
    this.data.data = result;
    this.storage.data.bookList = result;
  }
  reloadData(item) {
    const result = [];
    this.data.data.map((d) => {
      if (d.id === item.id) {
        result.push(item);
      } else {
        result.push(d);
      }
    });
    this.data.data = result;
  }
  refreshData(e) {
    // var callback = e.detail;
    // clearInterval(refreshTimer);
    this.data.data.map((item, index) => {
      item.loadStatus = true;
      let copy = Object.assign({}, item);
      this.reloadData(copy);
      this.searchService
        .searchBook({
          type: 2,
          id: item.sourceBookId,
        })
        .then((res) => {
          let resItem = Object.assign(item, res);
          resItem.loadStatus = false;
          resItem.currentChapter = copy.currentChapter;
          let obj = Object.assign({}, resItem);
          if (resItem.chapter.length != copy.chapter.length) {
            obj.isHaveUpdate = true;
          }
          this.reloadData(obj);
          const bookList = this.storage.data.bookList || [];
          bookList.map((item) => {
            const book = this.data.data.find((d) => d.id === item.id);
            if (book) {
              item = book;
            }
          });
          this.storage.data.bookList = bookList;
        });
    });
    // refreshTimer = setInterval(() => {
    //   let isF = false;
    //   this.data.data.map((item) => {
    //     if (isF) return;
    //     isF = item.loadStatus;
    //   });
    //   if (!isF) {
    //     clearInterval(refreshTimer);
    //     callback.success();
    //   }
    // }, 200);
  }
  /**
   * 跳转到查询页面
   */
  goToSearch() {
    this._wx.navigateTo({
      url: "../search/search",
    });
  }
  /**
   * 新增分组
   */
  addGroup() {
    this.data.showAddDialog = true;
    this.data.groupName = "";
  }

  tapDialogButton(e) {
    if (e.detail.index === 0) {
      this.data.showAddDialog = false;
    } else {
      const groupData = this.data.groupData;
      groupData.push({
        id: new Date().getTime(),
        name: this.data.groupName,
        bookList: [this.data.currentBookId],
      });
      this.data.groupData = this.storage.data.groups = groupData;
      this.data.showAddDialog = false;
      this.data.groupModalStatus = false;
      this.reloadPageData();
    }
  }

  changeInputText(e) {
    this.data.groupName = e.detail.value;
  }
}

new IndexController({
  data: [],
  currentBookId: "",
  groupData: [],
  showAddDialog: false,
  groupName: "",
  currentGroup: {},
  allData: {
    id: "all",
    name: "全部书籍",
    bookList: [],
  },
  buttons: [{ text: "取消" }, { text: "确定" }],
  defaultAddGroup: {
    id: "",
    name: "新增分组",
    bookList: [],
  },
  groupModalStatus: false,
});
